<?php
/**
 * DbReader
 * - Read the XML which specifies DB
 * - Read the template of DAO objects
 * - Generate code for DAO objects
 * @author Do Truong Giang
 */
include_once("BaseObject.class.php");
include_once("TplReader.class.php");
class DbReader extends BaseObject{
	private $tableInfo;
	/**
	 * Constructor
	 * - passing the dbFile, read and store information to attributes
	 */
	public function DbReader($dbFile) {
		$this->tableInfo = array();
		$this->getAllTableFromDB($dbFile);
		$dom = new DomDocument();
		$dom->load($dbFile);
		foreach ($dom->getElementsByTagName("table") as $tbl) {
			$tableName = $tbl->getAttribute("name");
			$tableClassName = $this->camelFormat($tableName);
			$primaryKey = $tbl->getAttribute("primaryKey");
			$this->tableInfo[] = array("name" => $tableName,
								"key" => $primaryKey,
								"className" => $tableClassName);
		}
	}
	
	/**
	 * generateCode
	 * - Auto create source code from file xml
	 */
	public function generateCode() {
		$tplReader = new TplReader();
		foreach ($this->tableInfo as $table) {
			$params = array("TABLE_NAME" => $table["name"],
							"CLASS_NAME" => $table["className"],
							"PRIMARY_KEY" => $table["key"],
							"FETCH_ALL_OF" => $this->getFunctionFetchAllOf($table),
							);
			$srcCode = $tplReader->read(DOCUMENT_ROOT . "/codegen/templates/db_template.xml", $params);
			$this->storeDbSourceCode($srcCode, $table["className"]);
		}
		
	}
	
	/**
	 * getFunctionFetchAllOf
	 * - content of function fetchAllOfxxx
	 * @param Array $table
	 * @return String : code
	 * @author Nguyen Thanh Quyen
	 * @since 1.0 - 05-05-2009
	 */
	private function getFunctionFetchAllOf($table){
		$code = "";
		$code .= "\$c = Criteria::factoryCriteria();\n";
		$code .= "		\$c->setTableNames(\"".$table['name']."\");\n";
		$code .= "		\$res = \$this->select(\$c);\n";
		$code .= "		return \$res;";
		return $code;
	}
	
	/**
	 * getAllTableFromDB
	 * - Read info of table from database and extract to file xml
	 * @param String $dbFile : the path of file configuration xml
	 * @author Nguyen Thanh Quyen
	 * @since 1.0 - 06-05-2009
	 */
	 private function getAllTableFromDB($dbFile){
	 	global $dbcon, $dbInfo;
	 	$srcCode = "";
	 	$handle = fopen($dbFile, "w");
	    $srcCode .= "<?xml version='1.0' encoding='UTF-8'?>\n";
		$srcCode .= "<configuration>\n";
	 	$m = $dbcon->query("SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.STATISTICS WHERE INDEX_NAME='PRIMARY' AND INDEX_SCHEMA='" . $dbInfo["database"] . "'");
	    $result = $m->fetchAll(PDO::FETCH_ASSOC);
	    foreach($result as $row){
	   		// Extract to file xml
	   		$table = $row['TABLE_NAME'];
	   		// Get primaryKey
	   		$primaryKey = $row['COLUMN_NAME'];
	   		$srcCode .= "      <table name='$table' primaryKey='$primaryKey'/>\n";
	   	}
	   	$srcCode .= "</configuration>\n";
	   	fwrite($handle, $srcCode);
	   	fclose($handle);
	 }
}
?>